var utils = {
	generateName: function (length) {
		if(typeof length === 'undefined') {
			length = 8;
		}

		var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		var name = '';
		var i = 0;

		while(i < length) {
			name += chars[Math.floor((Math.random() * (chars.length-1))+1)];
			i++;
		}

		return name;
	},
	getEventId: function (str) {
		if(typeof str == 'string'){
			var match, re;
			re = /\/(\d+)\//;
			match = str.match(re);
			if(match && match.length > 1){
				return match[1];
			}
		}
	},
	append: function (obj){
		var args, i, arg, key;
		args = Array.prototype.slice.call(arguments, 1);
		if(args.length > 0){
			for(var i = 0, l = args.length; i < l; i++){
				arg = args[i];
				for(key in arg){
					if(Object.prototype.hasOwnProperty.call(arg, key))
						obj[key] = arg[key];
				}
			}
		}
		return obj;
	},
	generateRandomCode: function(){
		return (Math.random() + "").match(/0\.0*(\d{6})/)[1];
	},
	range: function(num, step){ 
		var r = [];
		var step = step || 1;
		for(var i = 0; i < num; i++){ 
			r[i] = typeof r[i - 1] === 'undefined' ? 0 : r[i - 1] + step; 
		}
		return r;
	},
	luckyDraw: function(probability){
		if(!probability || probability >= 1 || probability <= 0){ 
			probability = 0.05;
		}
		var probability = probability * 100;
		var range = utils.range(100);
		range = range.shuffle();
		var lucky = range.slice(0, probability - 1);
		var seed = utils.random(100);
		return lucky.indexOf(seed) > -1;
	},
	random: function(min, max){ 
		if(typeof max === 'undefined'){ 
			max = min;
			min = 0;
		}
		return Math.floor(min + (max - min)*Math.random());
	}

}

Array.prototype.shuffle = function(){ 
	var srcArr = this,
		targetArr = [],
		i, length, item, randex, targetLastIndex, switchItem;
	for(i = 0, length = srcArr.length; i < length; i++){ 
		item = srcArr[i];
		targetLastIndex = targetArr.length;
		randex = utils.random(targetLastIndex);
		switchItem = targetArr[randex];
		targetArr[randex] = item;
		typeof switchItem !== 'undefined' && (targetArr[targetLastIndex] = switchItem);
	}
	return targetArr;
}
module.exports = utils;
